import { getSessionInfo, setSessionInfo } from '@/utils/storage'
import { TAGS_VIEW } from '@/constants'

const state = {
  tagsViewList: getSessionInfo(TAGS_VIEW) || []
}

const mutations = {
  /**
   * 添加 tags
   */
  ADD_TAGS_VIEW_LIST (state, tag) {
    const isFind = state.tagsViewList.find(item => {
      return item.path === tag.path
    })
    // 处理重复
    if (!isFind) {
      state.tagsViewList.push(tag)
      setSessionInfo(TAGS_VIEW, state.tagsViewList)
    }
  },
  /**
   * 为指定的 tag 修改 title
   */
  CHANGE_TAGS_VIEW (state, { index, tag }) {
    state.tagsViewList[index] = tag
    setSessionInfo(TAGS_VIEW, state.tagsViewList)
  },
  /**
   * 删除 tag
   * @param {type: 'other'||'right'||'index', index: index} payload
   */
  REMOVE_TAGS_VIEW (state, payload) {
    if (payload.type === 'index') {
      state.tagsViewList.splice(payload.index, 1)
      return
    } else if (payload.type === 'other') {
      state.tagsViewList.splice(
        payload.index + 1,
        state.tagsViewList.length - payload.index + 1
      )
      state.tagsViewList.splice(0, payload.index)
    } else if (payload.type === 'right') {
      state.tagsViewList.splice(
        payload.index + 1,
        state.tagsViewList.length - payload.index + 1
      )
    }
    setSessionInfo(TAGS_VIEW, state.tagsViewList)
  }
}

export default {
  namespaced: true,
  state,
  mutations
}
